﻿using LKVMLMADMIN.Common;
using LKVMLMADMIN.Models;
using LKVMLMLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Mvc;

namespace LKVMLMADMIN.Controllers.Html
{
    public class ChoNhanController : Controller
    {
        public LKVService.User db = new LKVService.User();
        public LKVMLMLib.ChoNhanService ch = new LKVMLMLib.ChoNhanService();
        public LKVMLMLib.Package pk = new LKVMLMLib.Package();
        
        public ActionResult PhongCho() 
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var showDataProvideRoom = from r in db.ProvideRooms join u in db.UserProfiles on r.UserId equals u.UserId select
                                              new RoomCodeModel
                                              {
                                                  UserId = u.UserId,
                                                  UserName = u.UserName,
                                                  RoomCode = r.RoomCode
                                              };
                var listUser = from u in db.UserProfiles join wr in db.WaitingProvideRooms on u.UserId equals wr.UserId select new WaitingRoom { UserId = u.UserId, UserName = u.UserName, Id = wr.Id };
                ViewBag.listProvideRoom = showDataProvideRoom.OrderBy(w=>w.RoomCode).ToList();
                ViewBag.listUserPhongCho = listUser.ToList();
                return View();
            }
        }
        public ActionResult PhongNhan()
        {

            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                DateTime date = DateTime.Now;
                date = date.AddDays(-10);
                var listReviewRoom2 = from r in db.ReviveRooms
                                          join u in db.UserProfiles on r.UserId equals u.UserId
                                          select
                                              new RoomCodeModel
                                              {
                                                  UserId = u.UserId,
                                                  UserName = u.UserName,
                                                  RoomCode = r.RoomCode
                                              };
                var listUser = from u in db.UserProfiles join wr in db.WaitingReceivedRooms on u.UserId equals wr.UserId select new WaitingRoom { UserId = u.UserId, UserName = u.UserName, Id = wr.Id };
                ViewBag.listReviewRoom2 = listReviewRoom2.OrderBy(w=>w.RoomCode).ToList();
                ViewBag.listUserPhongCho = listUser.ToList();
                return View();
            }
        }
        public JsonResult AddProvideRoom(string chuoi = "")
        {
            if (Session["User"] == null)
                return Json("", JsonRequestBehavior.AllowGet);
            if (String.IsNullOrEmpty(chuoi))
                return Json(new { Status = false, Result = "", Msg = "" });
            List<string> lsUserId = chuoi.Split(',').ToList();
            lsUserId.RemoveAt(lsUserId.Count - 1);
            var intUserId = new List<int>();
            lsUserId.ForEach(f=>{intUserId.Add(Convert.ToInt32(f));});       
            var maTheService = new PinService.Lib.MaThePaymentService();
            LKVMLMLib.ProvideRoom pro = new LKVMLMLib.ProvideRoom();
                if (lsUserId.Count == 4)
                {
                    // them moi roomCode
                    LKVMLMLib.RoomCode rc = new LKVMLMLib.RoomCode();
                    string roomCode = generateRoomCode();
                    rc.RoomCode1 = roomCode;
                    rc.Status = false;
                    rc.Use = false;
                    rc.CreateDate = DateTime.Now;
                    ch.addRoomCode(rc);
                    var temp = intUserId.ToList();
                    if (temp.Count > 0)
                        for (int i = 0; i < temp.Count; i++)
                        {
                            var waitingProvideRoom = ch.getWaitingProvideRoomById(temp[i]);
                            pro.UserId = waitingProvideRoom.UserId;
                            pro.RoomCode = roomCode;
                            ch.addNewProvideRoom(pro);
                            intUserId.Remove(temp[i]);
                            ch.deleteWaitingProvide(temp[i]);
                            try
                            {
                                var user = db.findUserById(Convert.ToInt32(waitingProvideRoom.UserId));
                                if (user != null)
                                {
                                    if (!String.IsNullOrEmpty(user.EMAIL))
                                    {
                                        MailHelper.SendMail(user.EMAIL, "Notication", "You are moved to Provide Room, please login to system to donate");
                                    }
                                }
                            }
                            catch (Exception)
                            {
                                continue;
                            }
                        }
                }
            return Json(new { Status = true, Result = "", Msg = "" }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult AddReviveRoom(string chuoi = "")
        {
            if (Session["User"] == null)
                return Json("", JsonRequestBehavior.AllowGet);
            if (String.IsNullOrEmpty(chuoi))
                return Json(new { Status = false, Result = "", Msg = "" });
            List<string> lsUserId = chuoi.Split(',').ToList();
            lsUserId.RemoveAt(lsUserId.Count - 1);
            var intUserId = new List<int>();
            string roomCode = "";
            if(ch.getRoomCode()!=null)
                roomCode = ch.getRoomCode().RoomCode1;
            lsUserId.ForEach(f => { intUserId.Add(Convert.ToInt32(f)); });
            var maTheService = new PinService.Lib.MaThePaymentService();
            LKVService.OrderService orderService = new LKVService.OrderService();
            string connection = DuAnDaCapEntities.getDomain();
            var libdb = LKVMLMLib.DuAnDaCapEntities.initDuAnDaCapEntities(connection);
            if (roomCode != "")
            {
                List<WaitingReceivedRoom> listTemp = new List<WaitingReceivedRoom>();
                var listProvideRoom = ch.getListProvideRoomByRoomCode(roomCode).Take(4).ToList();
                if (intUserId.Count >= 1 && intUserId.Count <= 2)
                {
                    foreach (var ls in intUserId)
                    {
                        var getWait = ch.getWaitingReviveRoomById(ls);
                        if (getWait != null)
                        {
                            listTemp.Add(new WaitingReceivedRoom { Id = ls, UserId = getWait.UserId, CreateDate = getWait.CreateDate, Action = getWait.Action });
                        }
                    }
                    for (int i = 0; i <= ch.getListWaitingReceivedRoom().Count; i++)
                    {
                        if (listTemp.Count == 3) break;
                        foreach (var a in ch.getListWaitingReceivedRoom())
                        {
                            if (listTemp.Count == 3) break;
                            if (listTemp.Find(w => w.Id == a.Id) == null && listProvideRoom.Find(w => w.UserId == a.UserId) == null)
                            {
                                //if (libdb.UserProfiles.Where(u => u.UserId == a.UserId).FirstOrDefault().GruopID != 3 && libdb.ReviveRooms.Where(u => u.UserId == a.UserId).ToList().Count >= 6)
                                //{
                                //    if (libdb.UserProfiles.Where(us => us.Parent_ID == a.UserId).ToList().Find(f => f.Status == true) != null)
                                //        if (listTemp.Where(w => w.UserId == a.UserId).FirstOrDefault() == null)
                                //            listTemp.Add(a);
                                //}
                                //else
                                //{
                                //    if (listTemp.Where(w => w.UserId == a.UserId).FirstOrDefault() == null)
                                //        listTemp.Add(a);
                                //}
                                listTemp.Add(a);
                            }
                        }
                    }
                    if (listTemp.Count < 3)
                    {
                        UserProfile user = new UserProfile();
                        Random ran = new Random();
                        var users = libdb.UserProfiles.Where(u => u.GruopID == 3).ToList();
                        int count = users.Count();
                        int index = new Random().Next(count);
                        if (listTemp.Find(w => w.UserId == users[index].UserId) == null&& listProvideRoom.Find(w=>w.UserId==users[index].UserId)==null)
                        {
                            user = users.Skip(index).FirstOrDefault();
                            if(user!=null)
                            listTemp.Add(new WaitingReceivedRoom{UserId=user.UserId});
                        }
                        users.Remove(users[index]);
                    }
                }
                if (listTemp.Count == 3)
                {
                    if (listProvideRoom.Count == 4)
                    {
                        foreach (var item in listProvideRoom)
                        {
                            var order = orderService.getListOrderByUserId(Convert.ToInt32(item.UserId)).Where(o => o.Action == false).FirstOrDefault();
                            if (order != null)
                            {
                                LKVMLMLib.ProvideOrder pro = new LKVMLMLib.ProvideOrder();
                                for (int i = 0; i < listTemp.Count; i++)
                                {
                                    //var waitingReviveRoom = ch.getWaitingReviveRoomById(Convert.ToInt32(lsUserId[i]));
                                    pro.OrderId = order.ID;
                                    pro.UserIdGive = item.UserId;
                                    pro.UserIdGet = listTemp[i].UserId;
                                    pro.Status = 0;
                                    pro.Amount = order.Amount / 3;
                                    pro.RoomCode = roomCode;
                                    ch.addNewProvideOrder(pro);
                                }
                            }
                        }
                        ch.UpdateUseRoomCode(roomCode);
                        LKVMLMLib.ReviveRoom re = new LKVMLMLib.ReviveRoom();
                        for (int j = 0; j < listTemp.Count; j++)
                        {
                            re.UserId = listTemp[j].UserId;
                            re.RoomCode = roomCode;
                            ch.addNewRevive(re);
                            if(listTemp[j].Id != 0)
                                ch.deleteWaitingRevieRoom(Convert.ToInt32(listTemp[j].Id));
                            try
                            {
                                var user2 = db.findUserById(Convert.ToInt32(listTemp[j].UserId));
                                if (user2 != null)
                                {
                                    if (!String.IsNullOrEmpty(user2.EMAIL))
                                    {
                                        MailHelper.SendMail(user2.EMAIL, "Notication", "You are moved to Revive Room, please login to system to donate");
                                    }
                                }
                            }
                            catch (Exception) { continue; }
                        }
                    }
                }
            }
            return Json(new { Status = true, Result = "", Msg = "" }, JsonRequestBehavior.AllowGet);
        }
        public string generateRoomCode()
        {
            return Extension.HtmlHelperExtensions.generateRandomString(10, 1);
        }

        public string generateIdOrder()
        {
            var od = new LKVService.OrderService();
            var countOd = od.getListOrder().Count();
            string idorder = string.Empty;
            if (countOd == 0)
                return Extension.HtmlHelperExtensions.generateRandomString(10, 1);
            for (int i = 0; i < countOd; i++)
            {
                idorder = Extension.HtmlHelperExtensions.generateRandomString(10, 1);
                var _kq = od.findOrderbyIDOrder(idorder);
                if (_kq == null)
                    break;
            }
            return idorder;
        }
        
    }

}
